<route lang="json5" type="page">
{
  style: {
    // navigationBarTitleText: '记录回忆',
    // backgroundColor: '#ffffff',
  },
}
</route>

<template>
  <view class="page">
    <!-- 顶部类型选择 -->
    <scroll-view class="type-scroll" scroll-x>
      <view class="type-list">
        <view
          class="type-item"
          :class="{ active: currentType === type.id }"
          v-for="type in memoryTypes"
          :key="type.id"
          @click="selectType(type.id)"
        >
          <image :src="type.icon" mode="aspectFill" class="type-icon" />
          <text class="type-name">{{ type.name }}</text>
        </view>
        <view class="type-item add-type" @click="showCreateType">
          <view class="add-icon">
            <wd-icon name="plus" size="32rpx" color="#94a3b8" />
          </view>
          <text class="type-name">新建</text>
        </view>
      </view>
    </scroll-view>

    <!-- 娃娃/角色选择器 -->
    <view v-if="currentType === 'doll'" class="doll-section">
      <view class="doll-grid" :class="{ 'is-expanded': isExpanded }">
        <!-- 显示前3个娃娃 -->
        <template v-if="!isExpanded">
          <view
            class="doll-item"
            :id="`doll-${doll.id}`"
            v-for="doll in visibleDolls"
            :key="doll.id"
            @click="selectDoll(doll.id)"
            @longpress="showDollActions(doll, $event)"
            :class="{ active: currentDoll === doll.id, 'is-pinned': doll.isPinned }"
          >
            <image :src="doll.avatar" mode="aspectFill" class="doll-avatar" />
            <text class="doll-name">{{ doll.name }}</text>
            <view class="pin-badge" v-if="doll.isPinned">
              <wd-icon name="pin" size="24rpx" color="#2563eb" />
            </view>
            <view class="edit-btn" @click.stop="editDoll(doll.id)">
              <wd-icon name="edit" size="24rpx" color="#94a3b8" />
            </view>
          </view>

          <!-- 超出数量显示 -->
          <view class="doll-item more-item" v-if="dolls.length > 3" @click="toggleExpand">
            <view class="more-avatar">
              <text>+{{ dolls.length - 3 }}</text>
            </view>
            <text class="doll-name">更多</text>
          </view>

          <!-- 新建按钮始终显示在最后 -->
          <view class="doll-item add-doll" @click="showCreateDoll">
            <view class="add-avatar">
              <image
                src=""
                class="plus-icon"
                mode="aspectFit"
              />
            </view>
            <text class="doll-name">新建娃娃</text>
          </view>
        </template>

        <!-- 展开后显示全部 -->
        <template v-else>
          <view
            class="doll-item"
            :id="`doll-${doll.id}`"
            v-for="doll in dolls"
            :key="doll.id"
            @click="selectDoll(doll.id)"
            @longpress="showDollActions(doll, $event)"
            :class="{ active: currentDoll === doll.id, 'is-pinned': doll.isPinned }"
          >
            <image :src="doll.avatar" mode="aspectFill" class="doll-avatar" />
            <text class="doll-name">{{ doll.name }}</text>
            <view class="pin-badge" v-if="doll.isPinned">
              <wd-icon name="pin" size="24rpx" color="#2563eb" />
            </view>
            <view class="edit-btn" @click.stop="editDoll(doll.id)">
              <wd-icon name="edit" size="24rpx" color="#94a3b8" />
            </view>
          </view>

          <view class="doll-item add-doll" @click="showCreateDoll">
            <view class="add-avatar">
              <image
                src=""
                class="plus-icon"
                mode="aspectFit"
              />
            </view>
            <text class="doll-name">新建娃娃</text>
          </view>
        </template>
      </view>

      <!-- 展开/收起按钮 -->
      <view class="expand-btn" v-if="dolls.length > 3" @click="toggleExpand">
        <text>{{ isExpanded ? '收起' : '展开' }}</text>
        <wd-icon :name="isExpanded ? 'up' : 'down'" size="24rpx" color="#64748b" />
      </view>
    </view>

    <!-- 文件夹/笔记本选择器 -->
    <scroll-view v-if="currentType === 'notebook'" class="notebook-scroll" scroll-x>
      <view class="notebook-list">
        <view
          class="notebook-item"
          :class="{ active: currentNotebook === notebook.id }"
          v-for="notebook in notebooks"
          :key="notebook.id"
          @click="selectNotebook(notebook.id)"
        >
          <view class="notebook-cover" :style="{ background: notebook.color }">
            <text class="notebook-title">{{ notebook.name }}</text>
          </view>
        </view>
        <view class="notebook-item add-notebook" @click="showCreateNotebook">
          <view class="add-cover">
            <wd-icon name="plus" size="48rpx" color="#94a3b8" />
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 搜索和过滤 -->
    <view class="search-section">
      <view class="search-bar">
        <wd-icon name="search" size="32rpx" color="#94a3b8" />
        <input
          v-model="searchQuery"
          class="search-input"
          placeholder="搜索回忆..."
          placeholder-class="search-placeholder"
          confirm-type="search"
          @confirm="handleSearch"
        />
        <view v-if="searchQuery" class="clear-btn" @click="clearSearch">
          <wd-icon name="close" size="28rpx" color="#94a3b8" />
        </view>
      </view>
    </view>

    <!-- 优化当前信息显示 -->
    <view class="collection-header">
      <view class="collection-info">
        <template v-if="currentType === 'doll'">
          <image :src="currentDollInfo?.avatar" class="avatar" mode="aspectFill" />
          <view class="info-text">
            <text class="name">{{ currentDollInfo?.name }}的回忆</text>
            <text class="count">
              共 {{ stats.totalMemories }} 篇回忆，{{ stats.totalFolders }} 个文件夹
            </text>
          </view>
        </template>
        <template v-else>
          <view class="notebook-icon" :style="{ background: currentNotebookInfo?.color }">
            <text class="icon-text">{{ currentNotebookInfo?.name?.[0] }}</text>
          </view>
          <view class="info-text">
            <text class="name">{{ currentNotebookInfo?.name }}</text>
            <text class="count">共 {{ filteredNotes.length }} 篇笔记</text>
          </view>
        </template>
      </view>

      <!-- 修改创建按钮为下拉菜单 -->
      <view class="create-dropdown">
        <view class="create-btn" @click="toggleCreateMenu">
          <wd-icon name="plus" size="32rpx" color="#2563eb" />
          <text>新建</text>
          <wd-icon :name="showCreateMenu ? 'up' : 'down'" size="24rpx" color="#2563eb" />
        </view>

        <!-- 下拉菜单 -->
        <view class="dropdown-menu" v-if="showCreateMenu" @click.stop>
          <view class="menu-item" @click="createNewNote">
            <wd-icon name="edit" size="32rpx" color="#64748b" />
            <text>新建回忆</text>
          </view>
          <view class="menu-item" @click="createNewFolder">
            <wd-icon name="folder" size="32rpx" color="#64748b" />
            <text>新建文件夹</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 笔记列表 -->
    <scroll-view
      v-if="currentDoll || currentNotebook"
      class="notes-scroll"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <view class="notes-list">
        <!-- 文件夹列表 -->
        <template v-if="folders.length > 0">
          <view class="folders-grid">
            <view
              class="folder-item"
              v-for="folder in folders"
              :key="folder.folderId"
              @click="openFolder(folder.folderId)"
            >
              <view class="folder-icon" :style="{ background: folder.color }">
                <i class="iconfont icon-wenjianjia"></i>
              </view>
              <view class="folder-info">
                <text class="folder-name">{{ folder.folderName }}</text>
                <text class="folder-count">{{ folder.memorial.length }}条回忆</text>
              </view>
              <view class="folder-actions">
                <i class="iconfont icon-more" @click.stop="showFolderActions(folder)"></i>
              </view>
            </view>
          </view>
        </template>

        <!-- 回忆列表 -->
        <template v-if="memories.length">
          <view
            class="memory-item"
            v-for="memory in memories"
            :key="memory.id"
            @click="openMemory(memory.id)"
          >
            <view class="memory-content">
              <text class="title">{{ memory.title || '无标题' }}</text>
              <text class="preview">{{ stripHtml(memory.content) }}</text>
              <view class="meta">
                <text class="time">{{ formatTime(memory.updateTime || memory.createTime) }}</text>
                <text class="location" v-if="memory.location">{{ memory.location }}</text>
              </view>
            </view>
            <view class="memory-cover" v-if="memory.images?.length">
              <image :src="memory.images[0]" mode="aspectFill" />
              <view class="media-badges">
                <view class="badge" v-if="memory.images.length > 1">
                  <wd-icon name="image" size="24rpx" color="#fff" />
                  <text>{{ memory.images.length }}</text>
                </view>
                <view class="badge" v-if="memory.hasAudio">
                  <wd-icon name="mic" size="24rpx" color="#fff" />
                </view>
                <view class="badge" v-if="memory.hasVideo">
                  <wd-icon name="video" size="24rpx" color="#fff" />
                </view>
              </view>
            </view>
          </view>
        </template>

        <!-- 空状态 -->
        <template v-if="memoriesStore.initialized && !folders.length && !memories.length">
          <view class="empty-state">
            <image src="/static/images/empty-notes.png" mode="aspectFit" class="empty-image" />
            <view class="empty-text">
              <text class="empty-title">还没有回忆</text>
              <text class="empty-desc">点击右下角的"+"开始记录吧</text>
            </view>
          </view>
        </template>
      </view>
    </scroll-view>

    <!-- 创建娃娃弹窗 -->
    <wd-popup v-model="showDollPopup" position="bottom" round>
      <view class="popup-content">
        <view class="popup-header">
          <text class="title">{{ editingDoll ? '编辑娃娃' : '创建娃娃' }}</text>
          <view class="close-btn" @click="showDollPopup = false">
            <wd-icon name="close" size="32rpx" color="#94a3b8" />
          </view>
        </view>
        <view class="doll-form">
          <view class="avatar-uploader" @click="chooseDollAvatar">
            <image
              v-if="dollForm.avatar"
              :src="dollForm.avatar"
              mode="aspectFill"
              class="preview"
            />
            <view v-else class="upload-placeholder">
              <wd-icon name="camera" size="48rpx" color="#94a3b8" />
              <text>点击上传头像</text>
            </view>
          </view>
          <input
            class="doll-name-input"
            v-model="dollForm.name"
            placeholder="给娃娃起个名字"
            placeholder-class="placeholder"
          />
          <view class="color-picker">
            <view
              class="color-item"
              v-for="color in dollColors"
              :key="color"
              :style="{ background: color }"
              :class="{ active: dollForm.color === color }"
              @click="dollForm.color = color"
            />
          </view>
          <view class="form-btns">
            <view class="submit-btn" @click="saveDoll">
              {{ editingDoll ? '保存' : '创建' }}
            </view>
          </view>
        </view>
      </view>
    </wd-popup>

    <!-- 上下文菜单应该放在这里 -->
    <view class="context-menu" v-if="showActionSheet" :style="menuPosition" @click.stop>
      <view
        class="menu-item"
        v-for="action in currentDollActions"
        :key="action.name"
        @click="handleDollAction(action)"
      >
        <wd-icon :name="action.icon" :color="action.color" size="32rpx" />
        <text :style="{ color: action.color }">{{ action.name }}</text>
      </view>
    </view>

    <!-- 添加创建文件夹弹窗 -->
    <wd-popup v-model="showFolderPopup" position="bottom" round>
      <view class="popup-content">
        <view class="popup-header">
          <text class="title">{{ editingFolder ? '编辑文件夹' : '新建文件夹' }}</text>
          <view class="close-btn" @click="showFolderPopup = false">
            <wd-icon name="close" size="32rpx" color="#94a3b8" />
          </view>
        </view>
        <view class="folder-form">
          <input
            class="folder-name-input"
            v-model="folderForm.name"
            placeholder="输入文件夹名称"
            placeholder-class="placeholder"
          />
          <view class="color-picker">
            <view
              class="color-item"
              v-for="color in folderColors"
              :key="color"
              :style="{ background: color }"
              :class="{ active: folderForm.color === color }"
              @click="folderForm.color = color"
            />
          </view>
          <view class="form-btns">
            <view class="submit-btn" @click="saveFolder">
              {{ editingFolder ? '保存' : '创建' }}
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onUnmounted, watch } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useNotesStore } from '@/store/notes'
import { useMemoriesStore } from '@/store/memories'
import type { Folder } from '@/store/memories'
import { useUIStore } from '@/store/ui'
import { useDollsStore } from '@/store/dolls'

const notesStore = useNotesStore()
const memoriesStore = useMemoriesStore()
const uiStore = useUIStore()
const dollsStore = useDollsStore()
const { currentNote } = storeToRefs(notesStore)

// 文件夹颜色选项 - 移到前面
const folderColors = [
  'linear-gradient(135deg, #60a5fa, #3b82f6)',
  'linear-gradient(135deg, #f472b6, #ec4899)',
  'linear-gradient(135deg, #fb923c, #f97316)',
  'linear-gradient(135deg, #4ade80, #22c55e)',
  'linear-gradient(135deg, #facc15, #eab308)',
  'linear-gradient(135deg, #a78bfa, #8b5cf6)',
]

// 添加文件夹相关的状态
const showFolderPopup = ref(false)
const editingFolder = ref<string | null>(null)
const folderForm = ref({
  name: '',
  color: folderColors[0],
})

// 获取文件夹列表
const folders = computed(() => {
  return memoriesStore.currentUserData?.folders.filter((f) => f.folderId !== 'default') || []
})

// 获取默认文件夹中的回忆列表
const memories = computed(() => {
  const defaultFolder = memoriesStore.currentUserData?.folders.find((f) => f.folderId === 'default')
  return defaultFolder?.memorial || []
})

// 添加 showCreateType 方法
const showCreateType = () => {
  uni.showToast({
    title: '功能开发中...',
    icon: 'none',
  })
}

// 记忆类型
const memoryTypes = [
  {
    id: 'doll',
    name: '解忧娃娃',
    icon: 'https://img.icons8.com/color/96/bear.png',
    type: 'collection',
  },
  {
    id: 'notebook', // 保留笔记本类型
    name: '笔记本',
    icon: 'https://img.icons8.com/color/96/moleskine.png',
    type: 'collection',
  },
  {
    id: 'diary',
    name: '日记',
    icon: 'https://img.icons8.com/color/96/story-book.png',
    type: 'note',
  },
]

// 集合列表（包含娃娃和笔记本）
const collections = ref([
  {
    id: 1,
    type: 'doll', // 娃娃类型
    name: '小布',
    avatar: 'https://api.dicebear.com/7.x/adventurer/svg?seed=doll1',
    color: '#60a5fa',
    notes: [
      {
        id: 1,
        title: '今天的心情',
        content: '...',
        createTime: '2024-03-20 14:30:00',
        images: [],
        location: '城市公园',
      },
    ],
  },
  {
    id: 2,
    type: 'diary', // 日记类型（默认笔记本）
    name: '我的日记',
    color: 'linear-gradient(135deg, #60a5fa, #3b82f6)',
    notes: [],
  },
])

// 当前选中的集合
const currentCollection = ref<number | null>(null)

// 使用 store 中的状态
const dolls = computed(() => dollsStore.sortedDolls)
const visibleDolls = computed(() => dollsStore.visibleDolls)
const currentDoll = computed({
  get: () => dollsStore.activeDollId,
  set: (id) => dollsStore.setActiveDoll(id),
})
const currentDollInfo = computed(() => dollsStore.currentDoll)

// 笔记本列表
const notebooks = ref([
  {
    id: 1,
    name: '生活记录',
    color: 'linear-gradient(135deg, #60a5fa, #3b82f6)',
  },
  {
    id: 2,
    name: '心情随笔',
    color: 'linear-gradient(135deg, #f472b6, #ec4899)',
  },
  {
    id: 3,
    name: '旅行日记',
    color: 'linear-gradient(135deg, #fb923c, #f97316)',
  },
])

// 娃娃颜色选项
const dollColors = [
  '#60a5fa', // 蓝色
  '#f472b6', // 粉色
  '#fb923c', // 橙色
  '#4ade80', // 绿色
  '#facc15', // 黄色
  '#a78bfa', // 紫色
]

// 文本工具
const textTools = [
  { name: 'bold', icon: 'bold' },
  { name: 'italic', icon: 'italic' },
  { name: 'underline', icon: 'underline' },
  { name: 'strike', icon: 'strike' },
  { name: 'align-left', icon: 'align-left' },
  { name: 'list', icon: 'list' },
]

// 媒体工具
const mediaTools = [
  { name: 'image', icon: 'image' },
  { name: 'video', icon: 'video' },
  { name: 'audio', icon: 'mic' },
  { name: 'attachment', icon: 'attachment' },
]

// 状态管理
const currentType = computed({
  get: () => uiStore.activeMemoryType,
  set: (value) => uiStore.setActiveMemoryType(value),
})
const currentNotebook = ref(1)
const showDollPopup = ref(false)
const editingDoll = ref(null)
const dollForm = ref({
  name: '',
  avatar: '',
  color: '#60a5fa',
})
const formData = ref({
  title: '',
  content: '',
})

// 当前选中的笔记本信息
const currentNotebookInfo = computed(() => {
  return notebooks.value.find((n) => n.id === currentNotebook.value)
})

// 当前笔记列表
const currentNotes = computed(() => {
  return notesStore.getNotesByCollection(
    currentType.value,
    currentType.value === 'doll' ? currentDoll.value : currentNotebook.value,
  )
})

// 打开笔记
const openNote = (id: number) => {
  const key =
    currentType.value === 'doll' ? `doll-${currentDoll.value}` : `notebook-${currentNotebook.value}`

  const note = notesStore.notesData[key]?.find((n) => n.id === id)
  if (!note) return

  // 跳转到编辑器页面
  uni.navigateTo({
    url: `/pages/memory/editor?id=${note.id}&type=${currentType.value}&collectionId=${
      currentType.value === 'doll' ? currentDoll.value : currentNotebook.value
    }`,
  })

  // 存储当前笔记到本地
  notesStore.setCurrentNote(note)
}

// 选择类型
const selectType = (type: string) => {
  currentType.value = type
  // 如果选择日记，自动选中默认日记本
  if (type === 'diary') {
    const diary = collections.value.find((c) => c.type === 'diary')
    if (diary) {
      currentCollection.value = diary.id
    }
  }
  // 如果选择笔记本，显示笔记本列表
  if (type === 'notebook') {
    showNotebookList.value = true
  }
}

// 选择娃娃
const selectDoll = (dollId: string) => {
  dollsStore.setActiveDoll(dollId)
  memoriesStore.setCurrentUser(dollId)
}

// 编辑娃娃
const editDoll = (id: number) => {
  const doll = dolls.value.find((d) => d.id === id)
  if (doll) {
    editingDoll.value = id
    dollForm.value = { ...doll }
    showDollPopup.value = true
  }
}

// 创建娃娃
const showCreateDoll = () => {
  editingDoll.value = null
  dollForm.value = {
    name: '',
    avatar: '',
    color: '#60a5fa',
  }
  showDollPopup.value = true
}

// 选择笔记本
const selectNotebook = (id: number) => {
  currentNotebook.value = id
  // 不再跳转，直接显示笔记列表
}

// 格式化时间
const { formatTime } = notesStore

// 检查是否包含媒体文件
const hasMedia = (note: any) => {
  return note.images?.length || note.hasAudio || note.hasVideo
}

// 编辑器实例
let editorCtx: any = null

// 编辑器准备完成
const onEditorReady = () => {
  uni
    .createSelectorQuery()
    .select('#editor')
    .context((res) => {
      editorCtx = res.context
    })
    .exec()
}

const onEditorInput = (e) => {
  formData.value.content = e.detail.html
}

// 处理工具点击
const handleTool = async (name: string) => {
  switch (name) {
    case 'image':
      const res = await uni.chooseImage({
        count: 9,
        sizeType: ['compressed'],
      })
      res.tempFilePaths.forEach((path) => {
        editorCtx?.insertImage({
          src: path,
          width: '100%',
          success: () => {
            console.log('插入图片成功')
          },
        })
      })
      break
    case 'video':
      const videoRes = await uni.chooseVideo()
      editorCtx?.insertVideo({
        src: videoRes.tempFilePath,
        width: '100%',
      })
      break
    case 'audio':
      startRecording()
      break
    default:
      editorCtx?.format(name)
  }
}

// 开始录音
const startRecording = () => {
  // TODO: 实现录音功能
  uni.showToast({
    title: '开始录音...',
    icon: 'none',
  })
}

// 选择位置
const openLocationPicker = async () => {
  try {
    const res = await uni.chooseLocation()
    editorCtx?.insertText({
      text: `📍 ${res.name}\n`,
    })
  } catch (e) {
    console.error(e)
  }
}

// 切换表情选择器
const toggleEmojiPicker = () => {
  // TODO: 实现表情选择器
  uni.showToast({
    title: '表情选择器开发中...',
    icon: 'none',
  })
}

// 保存记忆
const saveMemory = async () => {
  if (!currentCollection.value) {
    uni.showToast({ title: '请选择一个集合', icon: 'none' })
    return
  }

  const collection = collections.value.find((c) => c.id === currentCollection.value)
  if (!collection) return

  const newNote = {
    id: collection.notes.length + 1,
    title: formData.value.title,
    content: formData.value.content,
    createTime: new Date().toISOString(),
    images: [], // TODO: 处理图片上传
    location: '', // TODO: 处理位置信息
  }

  collection.notes.push(newNote)

  uni.showToast({ title: '保存成功', icon: 'success' })
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

// 选择娃娃/集合
const selectCollection = (id: number) => {
  currentCollection.value = id
  // 跳转到集合的笔记列表页面
  uni.navigateTo({
    url: `/pages/memory/collection?id=${id}`,
  })
}

// 刷新笔记列表
const isRefreshing = ref(false)
const onRefresh = () => {
  isRefreshing.value = true
  // 实现刷新逻辑
  isRefreshing.value = false
}

// 加载更多笔记
const loadMore = () => {
  // 实现加载更多逻辑
}

// Search and filter
const searchQuery = ref('')
const currentFilter = ref('all')
const showFilterTags = ref(true)

const filterOptions = [
  { label: '全部', value: 'all', icon: 'apps' },
  { label: '图片', value: 'image', icon: 'image' },
  { label: '音频', value: 'audio', icon: 'mic' },
  { label: '视频', value: 'video', icon: 'video' },
]

// Filtered notes
const filteredNotes = computed(() => {
  let notes = currentNotes.value

  // Apply search
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    notes = notes.filter(
      (note) =>
        note.title?.toLowerCase().includes(query) || note.content?.toLowerCase().includes(query),
    )
  }

  // Apply filters
  if (currentFilter.value !== 'all') {
    notes = notes.filter((note) => {
      switch (currentFilter.value) {
        case 'image':
          return note.images?.length > 0
        case 'audio':
          return note.hasAudio
        case 'video':
          return note.hasVideo
        default:
          return true
      }
    })
  }

  return notes
})

const handleSearch = () => {
  // Implement search logic if needed
}

const clearSearch = () => {
  searchQuery.value = ''
}

const setFilter = (filter: string) => {
  currentFilter.value = filter
}

// 选择娃娃头像
const chooseDollAvatar = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
    })

    // 显示上传中
    uni.showLoading({ title: '上传中...' })

    // 这里应该调用你的上传接口
    // 示例使用临时路径，实际应该上传到服务器
    dollForm.value.avatar = res.tempFilePaths[0]

    // 模拟上传延迟
    setTimeout(() => {
      uni.hideLoading()
    }, 500)
  } catch (e) {
    uni.showToast({
      title: '选择图片失败',
      icon: 'none',
    })
  }
}

// 保存娃娃信息
const saveDoll = () => {
  if (!dollForm.value.name.trim() || !dollForm.value.avatar) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none',
    })
    return
  }

  if (editingDoll.value) {
    dollsStore.updateDoll(editingDoll.value, {
      name: dollForm.value.name.trim(),
      avatar: dollForm.value.avatar,
      color: dollForm.value.color,
    })
  } else {
    const newDoll = dollsStore.addDoll({
      name: dollForm.value.name.trim(),
      avatar: dollForm.value.avatar,
      color: dollForm.value.color,
    })
    currentDoll.value = newDoll.id
  }

  showDollPopup.value = false
  resetDollForm()
}

// 展开状态也使用 store
const isExpanded = computed({
  get: () => uiStore.expandedDolls,
  set: (value) => uiStore.setExpandedDolls(value),
})

// 切换展开状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

// 添加操作菜单弹窗
const showActionSheet = ref(false)
const currentActionDoll = ref<any>(null)

// 操作菜单选项
const currentDollActions = computed(() => {
  const doll = currentActionDoll.value
  if (!doll) return []

  return [
    {
      name: '编辑娃娃',
      icon: 'edit',
      color: '#64748b',
    },
    {
      name: doll.isPinned ? '取消置顶' : '置顶娃娃',
      icon: 'pin',
      color: doll.isPinned ? '#94a3b8' : '#2563eb',
    },
    {
      name: '删除娃娃',
      icon: 'delete',
      color: '#ef4444',
    },
  ]
})

// 添加菜单位置状态
const menuPosition = ref('')

// 修改显示操作菜单方法
const showDollActions = (doll: any, event: any) => {
  currentActionDoll.value = doll

  // 直接使用事件位置
  const { clientX, clientY } = event.touches ? event.touches[0] : event

  // 获取屏幕尺寸
  const systemInfo = uni.getSystemInfoSync()
  const screenWidth = systemInfo.windowWidth
  const screenHeight = systemInfo.windowHeight

  // 计算菜单位置，显示在点击位置附近
  let x = clientX
  let y = clientY + 10 // 稍微往下偏移一点

  // 确保菜单不会超出屏幕
  if (x + 180 > screenWidth) {
    x = screenWidth - 180
  }
  if (y + 200 > screenHeight) {
    y = clientY - 160 // 如果底部空间不足，显示在上方
  }

  // 设置菜单位置
  menuPosition.value = `left: ${x}px; top: ${y}px;`

  // 显示菜单
  showActionSheet.value = true

  // 阻止事件冒泡
  event.stopPropagation?.()
}

// 修改关闭菜单的处理
const closeMenu = () => {
  showActionSheet.value = false
}

// 修改全局点击事件监听
onMounted(() => {
  // 添加全局点击事件来关闭菜单
  document.addEventListener('click', (event) => {
    const menu = document.querySelector('.context-menu')
    if (showActionSheet.value && menu && !menu.contains(event.target as Node)) {
      closeMenu()
    }
  })
})

onUnmounted(() => {
  // 清理事件监听
  document.removeEventListener('click', closeMenu)
})

// 修改菜单项点击处理
const handleDollAction = (action: any) => {
  const doll = currentActionDoll.value
  if (!doll) return

  switch (action.name) {
    case '编辑娃娃':
      editDoll(doll.id)
      break
    case '置顶娃娃':
    case '取消置顶':
      toggleDollPin(doll)
      break
    case '删除娃娃':
      deleteDoll(doll)
      break
  }
  closeMenu()
}

// 添加置顶和删除方法
const toggleDollPin = (doll: any) => {
  dollsStore.togglePin(doll.id)
}

const deleteDoll = (doll: { id: string; name: string }) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除"${doll.name}"吗？`,
    success: (res) => {
      if (res.confirm) {
        dollsStore.deleteDoll(doll.id)
        uni.showToast({
          title: '删除成功',
          icon: 'success',
        })
      }
    },
  })
}

// 添加新的响应式变量
const showCreateMenu = ref(false)

// 切换创建菜单
const toggleCreateMenu = (event: Event) => {
  event.stopPropagation()
  showCreateMenu.value = !showCreateMenu.value
}

// 创建新文件夹
const createNewFolder = () => {
  showCreateMenu.value = false
  folderForm.value = {
    name: '',
    color: folderColors[0],
  }
  showFolderPopup.value = true
}

// 监听全局点击以关闭菜单
onMounted(() => {
  document.addEventListener('click', () => {
    if (showCreateMenu.value) {
      showCreateMenu.value = false
    }
  })
})

onUnmounted(() => {
  document.removeEventListener('click', () => {
    showCreateMenu.value = false
  })
})

// 保存文件夹
const saveFolder = () => {
  if (!folderForm.value.name.trim()) {
    uni.showToast({
      title: '请输入文件夹名称',
      icon: 'none',
    })
    return
  }

  if (editingFolder.value) {
    const folder = folders.value.find((f) => f.folderId === editingFolder.value)
    if (folder) {
      folder.folderName = folderForm.value.name.trim()
      folder.color = folderForm.value.color
      folder.updateTime = new Date().toISOString()
      memoriesStore.save()
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      })
    }
  } else {
    const newFolder = memoriesStore.createFolder(folderForm.value.name, folderForm.value.color)
    if (newFolder) {
      uni.showToast({
        title: '创建成功',
        icon: 'success',
      })
    }
  }

  showFolderPopup.value = false
  editingFolder.value = null
  folderForm.value = {
    name: '',
    color: folderColors[0],
  }
}

// 编辑文件夹
const editFolder = (id: string) => {
  const folder = folders.value.find((f) => f.folderId === id)
  if (folder) {
    editingFolder.value = id
    folderForm.value = {
      name: folder.folderName,
      color: folder.color,
    }
    showFolderPopup.value = true
  }
}

// 打开文件夹
const openFolder = (folderId: string) => {
  uni.navigateTo({
    url: `/pages/memory/folder?id=${folderId}`,
  })
}

// 显示文件夹操作菜单
const showFolderActions = (folder: Folder) => {
  uni.showActionSheet({
    itemList: ['编辑文件夹', '删除文件夹'],
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          editFolder(folder.folderId)
          break
        case 1:
          deleteFolder(folder.folderId)
          break
      }
    },
  })
}

// 删除文件夹
const deleteFolder = (id: string) => {
  uni.showModal({
    title: '确认删除',
    content: '删除文件夹将同时删除其中的所有回忆，确定要删除吗？',
    success: (res) => {
      if (res.confirm) {
        memoriesStore.deleteFolder(id)
        uni.showToast({
          title: '删除成功',
          icon: 'success',
        })
      }
    },
  })
}

// 创建新回忆
const createNewNote = () => {
  showCreateMenu.value = false
  const memory = memoriesStore.createMemory('新的回忆', 'default')
  if (memory) {
    uni.navigateTo({
      url: `/pages/memory/editor?id=${memory.id}&folderId=default`,
    })
  }
}

// 打开回忆
const openMemory = (id: number) => {
  uni.navigateTo({
    url: `/pages/memory/editor?id=${id}&folderId=default`,
  })
}

// 修改初始化部分
onMounted(async () => {
  try {
    // 确保 store 已初始化
    if (!memoriesStore.initialized) {
      await memoriesStore.init()
    }

    // 如果有当前选中的娃娃，设置为当前用户
    if (currentDoll.value) {
      memoriesStore.setCurrentUser(currentDoll.value)
    }

    // 初始化笔记数据
    if (notesStore.init) {
      await notesStore.init()
    }
  } catch (error) {
    console.error('Failed to initialize:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none',
    })
  }
})

// 修改 watch 部分，避免重复初始化
watch(currentDoll, (newId) => {
  if (newId && memoriesStore.initialized) {
    memoriesStore.setCurrentUser(newId)
  }
})

// 添加页面显示时的处理
onShow(() => {
  // 页面显示时重新获取最新数据，但不重新初始化
  if (memoriesStore.initialized) {
    memoriesStore.refresh()
  }
})

// 添加页面隐藏时的处理
onHide(() => {
  // 页面隐藏时保存当前状态
  if (memoriesStore.initialized) {
    memoriesStore.save()
  }
})

// 获取当前用户的统计数据
const stats = computed(() => {
  const userData = memoriesStore.currentUserData
  if (!userData) return { totalMemories: 0, totalFolders: 0 }

  const totalFolders = userData.folders.filter((f) => f.folderId !== 'default').length
  const totalMemories = userData.folders.reduce((sum, folder) => sum + folder.memorial.length, 0)

  return {
    totalFolders,
    totalMemories,
  }
})

// 重置娃娃表单
const resetDollForm = () => {
  editingDoll.value = null
  dollForm.value = {
    name: '',
    avatar: '',
    color: '#60a5fa',
  }
}

// Base64 编码的 SVG 图标
const folderIconBase64 =
  ''

const moreIconBase64 =
  ''

function stripHtml(html: string): string {
  // 移除所有HTML标签
  return (
    html
      .replace(/<[^>]*>/g, '')
      // 替换常见HTML实体
      .replace(/&nbsp;/g, ' ')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&amp;/g, '&')
      .replace(/&quot;/g, '"')
      // 移除多余空格
      .trim()
  )
}
</script>

<style lang="scss" scoped>
@import '../../styles/index';

.page {
  min-height: 100vh;
  padding-bottom: env(safe-area-inset-bottom);
  background: #f8fafc;
}

.type-scroll {
  padding: 20rpx 0;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;

  .type-list {
    display: flex;
    gap: 24rpx;
    padding: 0 20rpx;

    .type-item {
      display: flex;
      flex-direction: column;
      gap: 8rpx;
      align-items: center;
      padding: 16rpx;
      border-radius: 16rpx;
      transition: all 0.3s;

      &.active {
        background: #eff6ff;

        .type-name {
          color: #2563eb;
        }
      }

      .type-icon {
        width: 80rpx;
        height: 80rpx;
        border-radius: 20rpx;
      }

      .type-name {
        font-size: 24rpx;
        color: #64748b;
      }
    }

    .add-type {
      .add-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        background: #f1f5f9;
        border-radius: 20rpx;
      }
    }
  }
}

.doll-section {
  padding: 32rpx 24rpx;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;

  .doll-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16rpx;

    .doll-item {
      position: relative;
      display: flex;
      flex-direction: column;
      gap: 8rpx;
      align-items: center;
      padding: 12rpx;
      border-radius: 12rpx;
      transition: all 0.3s;

      &:active {
        background: #f8fafc;
      }

      &.active {
        .doll-avatar {
          border: 4rpx solid #2563eb;
        }

        .doll-name {
          color: #2563eb;
        }
      }

      .doll-avatar {
        width: 100rpx;
        height: 100rpx;
        border: 4rpx solid transparent;
        border-radius: 50rpx;
        transition: all 0.3s;
      }

      .doll-name {
        width: 100%;
        font-size: 24rpx;
        color: #64748b;
        text-align: center;
        @include line-clamp(1);
      }

      .edit-btn {
        position: absolute;
        top: 4rpx;
        right: 4rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36rpx;
        height: 36rpx;
        background: #fff;
        border-radius: 50%;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }

      &.more-item {
        .more-avatar {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100rpx;
          height: 100rpx;
          background: #f1f5f9;
          border-radius: 50rpx;

          text {
            font-size: 28rpx;
            font-weight: 600;
            color: #64748b;
          }
        }
      }

      &.add-doll {
        .add-avatar {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100rpx;
          height: 100rpx;
          background: #f1f5f9;
          border-radius: 50rpx;

          .plus-icon {
            width: 40rpx;
            height: 40rpx;
          }
        }
      }

      &.is-pinned {
        .doll-avatar {
          border-color: #2563eb;
        }
      }

      .pin-badge {
        position: absolute;
        top: 4rpx;
        left: 4rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36rpx;
        height: 36rpx;
        background: #eff6ff;
        border-radius: 50%;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }
    }
  }

  .expand-btn {
    display: flex;
    gap: 8rpx;
    align-items: center;
    justify-content: center;
    padding: 12rpx;
    margin-top: 16rpx;
    font-size: 26rpx;
    color: #64748b;

    &:active {
      opacity: 0.8;
    }
  }
}

.notebook-scroll {
  padding: 32rpx 0;
  background: #fff;

  .notebook-list {
    display: flex;
    gap: 32rpx;
    padding: 0 32rpx;

    .notebook-item {
      .notebook-cover {
        display: flex;
        align-items: flex-end;
        width: 160rpx;
        height: 200rpx;
        padding: 20rpx;
        border-radius: 16rpx;

        .notebook-title {
          font-size: 24rpx;
          color: #fff;
          text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
        }
      }
    }

    .add-notebook {
      .add-cover {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 160rpx;
        height: 200rpx;
        background: #f1f5f9;
        border-radius: 16rpx;
      }
    }
  }
}

.search-section {
  padding: 24rpx;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;

  .search-bar {
    display: flex;
    align-items: center;
    padding: 20rpx 24rpx;
    background: #f1f5f9;
    border-radius: 16rpx;

    .search-input {
      flex: 1;
      margin-left: 16rpx;
      font-size: 28rpx;
    }

    .clear-btn {
      padding: 8rpx;
    }
  }
}

.collection-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 24rpx;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;

  .collection-info {
    display: flex;
    gap: 20rpx;
    align-items: center;

    .avatar {
      width: 88rpx;
      height: 88rpx;
      border-radius: 44rpx;
    }

    .notebook-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 88rpx;
      height: 88rpx;
      border-radius: 24rpx;

      .icon-text {
        font-size: 36rpx;
        font-weight: 600;
        color: #fff;
      }
    }

    .info-text {
      display: flex;
      flex-direction: column;
      gap: 8rpx;

      .name {
        font-size: 32rpx;
        font-weight: 600;
        color: #0f172a;
      }

      .count {
        font-size: 24rpx;
        color: #64748b;
      }
    }
  }

  // 修改创建按钮为下拉菜单
  .create-dropdown {
    position: relative;

    .create-btn {
      display: flex;
      gap: 8rpx;
      align-items: center;
      padding: 16rpx 24rpx;
      font-size: 28rpx;
      color: #2563eb;
      background: #eff6ff;
      border-radius: 32rpx;
      transition: all 0.2s;

      &:active {
        opacity: 0.8;
      }
    }

    .dropdown-menu {
      position: absolute;
      top: 100%;
      right: 0;
      z-index: 100;
      width: 240rpx;
      padding: 8rpx;
      margin-top: 8rpx;
      background: #fff;
      border-radius: 12rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
      transform-origin: top right;
      animation: dropdownPop 0.2s ease-out;

      .menu-item {
        display: flex;
        gap: 12rpx;
        align-items: center;
        padding: 20rpx 24rpx;
        font-size: 28rpx;
        color: #1f2937;
        border-radius: 8rpx;
        transition: all 0.2s;

        &:active {
          background: #f1f5f9;
        }
      }
    }
  }
}

.notes-scroll {
  flex: 1;
  height: calc(100vh - 380rpx);
  overflow: hidden;
  background: #f8fafc;
}

.notes-list {
  min-height: calc(100vh - 480rpx); // 确保有足够空间显示空状态
  padding: 24rpx;

  .folders-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24rpx;
    padding-bottom: 24rpx;
    margin-bottom: 24rpx;
    border-bottom: 1px solid #e2e8f0;

    .folder-item {
      display: flex;
      gap: 16rpx;
      align-items: center;
      padding: 20rpx;
      background: #fff;
      border-radius: 16rpx;
      transition: all 0.2s;

      &:active {
        opacity: 0.8;
      }

      .folder-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 88rpx;
        height: 88rpx;
        border-radius: 20rpx;

        .iconfont {
          font-size: 60rpx;
          color: #3b82f6;
        }
      }

      .folder-info {
        flex: 1;
        overflow: hidden;

        .folder-name {
          display: block;
          font-size: 28rpx;
          font-weight: 500;
          color: #0f172a;
          @include line-clamp(1);
        }

        .folder-count {
          font-size: 24rpx;
          color: #64748b;
        }
      }

      .folder-actions {
        padding: 12rpx;
        margin-right: -8rpx;

        .iconfont {
          font-size: 36rpx;
          -webkit-text-fill-color: #94a3b8;
          -webkit-text-stroke-color: #94a3b8;
          opacity: 0.75;
          transition: all 0.2s;
        }

        &:active {
          .iconfont {
            opacity: 0.9;
          }
        }
      }
    }
  }

  .memory-item {
    display: flex;
    gap: 24rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    background: #fff;
    border-radius: 16rpx;

    .memory-content {
      flex: 1;

      .title {
        display: block;
        margin-bottom: 16rpx;
        font-size: 32rpx;
        font-weight: 500;
        color: #0f172a;
      }

      .preview {
        display: block;
        margin-bottom: 24rpx;
        font-size: 28rpx;
        color: #64748b;
        @include line-clamp(3);
      }

      .meta {
        display: flex;
        gap: 16rpx;
        align-items: center;

        .time,
        .location {
          font-size: 24rpx;
          color: #94a3b8;
        }
      }
    }

    .memory-cover {
      position: relative;
      width: 200rpx;
      height: 200rpx;
      overflow: hidden;
      border-radius: 12rpx;

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .media-badges {
        position: absolute;
        right: 8rpx;
        bottom: 8rpx;
        display: flex;
        gap: 8rpx;

        .badge {
          display: flex;
          gap: 4rpx;
          align-items: center;
          padding: 4rpx 8rpx;
          background: rgba(0, 0, 0, 0.5);
          border-radius: 8rpx;

          text {
            font-size: 24rpx;
            color: #fff;
          }
        }
      }
    }
  }

  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 48rpx;
    text-align: center;

    .empty-image {
      width: 320rpx;
      height: 120rpx;
      margin-bottom: 48rpx;
      opacity: 0.8;
    }

    .empty-text {
      display: flex;
      flex-direction: column;
      gap: 12rpx;
      align-items: center;

      .empty-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #0f172a;
      }

      .empty-desc {
        font-size: 28rpx;
        color: #64748b;
      }
    }
  }
}

.popup-content {
  padding: 32rpx;

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32rpx;

    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #0f172a;
    }

    .close-btn {
      padding: 8rpx;
    }
  }

  .doll-form {
    .avatar-uploader {
      width: 160rpx;
      height: 160rpx;
      margin: 0 auto 32rpx;
      cursor: pointer;
      transition: all 0.3s;

      &:active {
        opacity: 0.8;
      }

      .preview {
        width: 100%;
        height: 100%;
        border: 4rpx solid #e2e8f0;
        border-radius: 80rpx;
      }

      .upload-placeholder {
        display: flex;
        flex-direction: column;
        gap: 12rpx;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: #f1f5f9;
        border: 4rpx dashed #e2e8f0;
        border-radius: 80rpx;

        text {
          font-size: 24rpx;
          color: #94a3b8;
        }
      }
    }

    .doll-name-input {
      width: 100%;
      height: 88rpx;
      padding: 0 24rpx;
      margin-bottom: 32rpx;
      font-size: 28rpx;
      background: #f8fafc;
      border-radius: 16rpx;
    }

    .color-picker {
      display: flex;
      gap: 16rpx;
      justify-content: center;
      margin-bottom: 48rpx;

      .color-item {
        width: 48rpx;
        height: 48rpx;
        border: 4rpx solid transparent;
        border-radius: 24rpx;

        &.active {
          border-color: #fff;
          box-shadow: 0 0 0 4rpx #2563eb;
        }
      }
    }

    .form-btns {
      display: flex;
      gap: 24rpx;

      .submit-btn {
        background: linear-gradient(135deg, #3b82f6, #2563eb);

        &:active {
          transform: scale(0.98);
        }
      }
    }
  }
}

.placeholder {
  color: #94a3b8;
}

// 添加空状态样式
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 48rpx;
  text-align: center;

  .empty-image {
    width: 320rpx;
    height: 320rpx;
    margin-bottom: 48rpx;
    opacity: 0.8;
  }

  .empty-text {
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    align-items: center;

    .empty-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #0f172a;
    }

    .empty-desc {
      font-size: 28rpx;
      color: #64748b;
    }
  }
}

// 添加长按反馈效果
.doll-item {
  &:active {
    opacity: 0.8;
    transition: opacity 0.2s;
  }
}

// 添加上下文菜单样式
.context-menu {
  position: fixed;
  z-index: 1000;
  min-width: 180rpx;
  padding: 8rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  transform-origin: top left;
  animation: menuPop 0.2s ease-out;

  .menu-item {
    display: flex;
    gap: 12rpx;
    align-items: center;
    padding: 20rpx 24rpx;
    font-size: 28rpx;
    color: #1f2937;
    border-radius: 8rpx;
    transition: all 0.2s;

    &:active {
      background: #f1f5f9;
    }

    .wd-icon {
      margin-right: 8rpx;
    }
  }
}

@keyframes menuPop {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes dropdownPop {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

// 添加文件夹表单样式
.folder-form {
  .folder-name-input {
    width: 100%;
    height: 88rpx;
    padding: 0 24rpx;
    margin-bottom: 32rpx;
    font-size: 28rpx;
    background: #f8fafc;
    border-radius: 16rpx;
  }

  .color-picker {
    display: flex;
    gap: 16rpx;
    justify-content: center;
    margin-bottom: 48rpx;

    .color-item {
      width: 48rpx;
      height: 48rpx;
      border: 4rpx solid transparent;
      border-radius: 24rpx;

      &.active {
        border-color: #fff;
        box-shadow: 0 0 0 4rpx #2563eb;
      }
    }
  }
}

.action-icon {
  width: 32rpx;
  height: 32rpx;
  opacity: 0.6;
}
</style>
